package com.dong.mjblog.controller;

import com.dong.mjblog.dto.FileDTO;
import com.dong.mjblog.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class FileController {

    @Autowired
    private UploadService uploadService;

    @PostMapping(value = "/file/upload")
    @ResponseBody
    public FileDTO upload(@RequestParam(value = "editormd-image-file",required = false) MultipartFile file,
                                             HttpServletRequest request,
                                             HttpServletResponse response){
        UploadService.UploadImgParam uploadImgParam = uploadService.new UploadImgParam();
        //判断是否需要生成缩略图
        if(request.getParameter("imgWidth")!=null && request.getParameter("imgHeight")!=null){
            uploadImgParam.setImgWidth(Integer.parseInt(request.getParameter("imgWidth")));
            uploadImgParam.setImgHeight(Integer.parseInt(request.getParameter("imgHeight")));
            if(request.getParameter("cutType")!=null) {
                uploadImgParam.setImgCutType(request.getParameter("cutType").toString());
            }
        }
        UploadService.UploadResult uploadResult = uploadService.uploadImg(file, uploadImgParam);
        FileDTO fileDTO = new FileDTO();
        fileDTO.setMessage(uploadResult.getMsg());
        fileDTO.setSuccess(uploadResult.getResult());
        fileDTO.setUrl(uploadResult.getSavePath());
        return fileDTO;
    }
}
